'''
Created on 01/05/2010

@author: Mar
'''
import time
from ThreadResource import ThreadResource
from queue import Queue

class IOResource:
        
    def __init__(self, name, numberOfInstances, readyQueue, anOutputQueue):
        self.readyQueue = readyQueue
        self.outputQueue = anOutputQueue
        self.name = name
        self.queue = Queue()
        self.numberOfInstances = numberOfInstances
        self.resourceThreads = {}
        
        for i in range(numberOfInstances):
            threadID = name + str(i)
            resourceThread  = ThreadResource(threadID, self)
            resourceThread.setDaemon(True)
            self.resourceThreads[threadID] = resourceThread 

    def put(self, aPCB):
        self.queue.put(aPCB)
        
    def startUp(self):
        for thread in self.resourceThreads.values():
            thread.start()

        
    def getReadyQueue(self):
        return self.readyQueue
    
    def setReadyQueue(self, aQueue):
        self.readyQueue = aQueue
            
    def executePCB(self, aPCB):
        self.execute(aPCB.getCurrentInstruction()) 
        aPCB.advance()
        
       
                
    def execute(self, anInst):
        self.outputQueue.put((anInst.getWord(),anInst.getTime()))
        print (anInst.getWord())
        time.sleep(anInst.getTime())
               
        
    def sendToReady(self, aPCB):
        self.getReadyQueue().put(aPCB)